package com.sdgs.paas.sdk.core.utils;

import java.util.HashMap;
import java.util.Map;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.sdgs.paas.sdk.core.log.PaasLogger;

public class ExpressionUtils {
	private static final ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");

	public static void main(String args[]) throws ScriptException {

		Map<String, String> map = new HashMap<>();
		map.put("a", "");
		map.put("b", "2");
		System.out.println(eval("a==b", map));
	}

	public static boolean eval(String exp, Map<String, String> var) throws ScriptException {
		long start = System.currentTimeMillis();
		Compilable ce = (Compilable) engine;
		CompiledScript cs = ce.compile(exp);
		Bindings bindings = engine.createBindings();
		bindings.putAll(var);
		boolean result = (boolean) cs.eval(bindings);
		PaasLogger.metricInfo("表达式：{}，执行耗时：{}", exp, System.currentTimeMillis() - start);
		return result;
	}

}